"use strict";
const BasicController = require("./basic");
const svgCaptcha = require("svg-captcha");
const fs = require("fs");
const path = require("path");
class UtilController extends BasicController {
      async captcha() {
            const captcha = svgCaptcha.create({
                  size: 4,
                  fontSize: 50,
                  width: 100,
                  height: 40,
                  noise: 3,
            });

            this.ctx.session.captcha = captcha.text;
            this.ctx.response.type = "image/svg+xml";
            this.ctx.body = captcha.data;
      }

      async sendEmailCode() {
            let { ctx, service } = this;
            let email = ctx.query.email;

            // 生成随机验证码
            const emailCode = String(Math.random()).substring(3, 9);
            // 保存随机验证码到session里
            ctx.session.emailCode = emailCode;

            const templatePath = path.resolve(__dirname, "../../template/captcha.html")
            const htmlEle = fs.readFileSync(templatePath, { encoding: "utf-8" });

            // 编写邮件格式，后期可以尝试模板
            const subject = "胖子验证码";
            const text = "";
            const html = htmlEle.replace("{{code}}", emailCode);

            // 发送邮件
            const { message, success } = await service.tools.sendMail(
                  email,
                  subject,
                  text,
                  html
            );

            if (success) {
                  return this.message(message);
            }

            this.error("发送失败", message);
      }
}

module.exports = UtilController;
